package com.imis.base.shiro.util;

import com.imis.base.constant.HttpHeadersConstants;
import com.imis.base.util.SpringContextUtils;
import com.imis.base.util.form.model.DataPermissionRuleModel;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * DataAuthorUtils<br>
 *
 * </p>
 *
 * @author XinLau
 * @version 1.0
 * @since 2020年10月22日 11:37
 */
public class DataAuthorUtils {

    /**
     * 往链接请求里面，传入数据查询条件
     *
     * @param request
     * @param dataRules
     */
    public static synchronized void installDataSearchCondition(HttpServletRequest request, List<DataPermissionRuleModel> dataRules) {
        @SuppressWarnings("unchecked")
        // 1.先从request获取 MENU_DATA_AUTHOR_RULES，如果存则获取到 LIST
        List<DataPermissionRuleModel> list = loadDataSearchConditionList();
        if (list == null) {
            // 2.如果不存在，则 new 一个 List
            list = new ArrayList<>();
        }
        for (DataPermissionRuleModel tsDataRule : dataRules) {
            list.add(tsDataRule);
        }
        // 3.往list里面增量存指
        request.setAttribute(HttpHeadersConstants.MENU_DATA_AUTHOR_RULES, list);
    }

    /**
     * 获取请求对应的数据权限规则
     *
     * @return
     */
    @SuppressWarnings("unchecked")
    public static synchronized List<DataPermissionRuleModel> loadDataSearchConditionList() {
        return (List<DataPermissionRuleModel>) SpringContextUtils.getHttpServletRequest().getAttribute(HttpHeadersConstants.MENU_DATA_AUTHOR_RULES);
    }

    /**
     * 获取请求对应的数据权限SQL
     *
     * @return
     */
    public static synchronized String loadDataSearchConditionString() {
        return (String) SpringContextUtils.getHttpServletRequest().getAttribute(HttpHeadersConstants.MENU_DATA_AUTHOR_RULE_SQL);
    }

    /**
     * 往链接请求里面，传入数据查询条件
     *
     * @param request
     * @param sql
     */
    public static synchronized void installDataSearchCondition(HttpServletRequest request, String sql) {
        String ruleSql = loadDataSearchConditionString();
        if (!StringUtils.hasText(ruleSql)) {
            request.setAttribute(HttpHeadersConstants.MENU_DATA_AUTHOR_RULE_SQL, sql);
        }
    }

}
